package com.zsk.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.utils.DateUtils;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopOrderPointsToAccount;
import com.zsk.shop.enums.EnumUserAccountChangeType;
import com.zsk.shop.mapper.ShopOrderPointsToAccountMapper;
import com.zsk.shop.model.params.MoneyAccountInsertParams;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljh
 * @create 2022/2/21 13:52
 */
@Service
public class ShopOrderPointsToAccountService extends ServiceImpl<ShopOrderPointsToAccountMapper, ShopOrderPointsToAccount> {

    @Resource
    private UserAccountService userAccountService;

    /**
     * 定时处理 余额临时表 转 用户余额的操作
     */
    public void task(Date day) {
        LambdaQueryWrapper<ShopOrderPointsToAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopOrderPointsToAccount::getIsResult, false);
        queryWrapper.eq(ShopOrderPointsToAccount::getType, 1);
        queryWrapper.le(ShopOrderPointsToAccount::getCreateTime, DateUtils.getDateEnd(day));
        queryWrapper.ge(ShopOrderPointsToAccount::getCreateTime, DateUtils.getDateStart(day));
        List<ShopOrderPointsToAccount> listAll = list(queryWrapper);
        if (ToolUtil.isEmpty(listAll)) {
            return;
        }
        List<String> userNoList = listAll.stream().map(ShopOrderPointsToAccount::getUserNo).collect(Collectors.toList());
        userNoList = userNoList.stream().filter(x -> ToolUtil.isNotEmpty(x)).distinct().collect(Collectors.toList());
        //定义一个
        for (String userNo : userNoList) {
            List<ShopOrderPointsToAccount> userShopOrderPointsAll = listAll.stream().filter(x -> x.getUserNo().equals(userNo)).collect(Collectors.toList());
            String money = userShopOrderPointsAll.stream().map(ShopOrderPointsToAccount::getChangeMoney).reduce(BigDecimal.ZERO, BigDecimal::add).toString();
            MoneyAccountInsertParams params = MoneyAccountInsertParams.builder()
                    .userNo(userNo).changeType(EnumUserAccountChangeType.POINT_TO_ACCOUNT.getCode()).money(money)
                    .orderNo("").build();
            userAccountService.moneyAccountInsert(params);
        }
        //所有变为已结算
        Date time = new Date();
        for (ShopOrderPointsToAccount shopOrderPointsToAccount : listAll) {
            shopOrderPointsToAccount.setIsResult(true);
            shopOrderPointsToAccount.setResultTime(time);
        }
        this.saveOrUpdateBatch(listAll);
    }

}
